
<?php
	/**
	* @package ParkFind
	* @desc This is the loginscript. This script is used check whether the user exists or not and checks the database, which will then run the loginreceipt.php file.
	*/

	// Direct calling check
	if (!isset($_POST["email"]))
		die("Do not call this page directly");
		
	session_start();	
	/**
	* @desc This include file connects to the database.
	*/
	require 'includes/connect.inc';

	// Store variables and clean them
	$email = mysql_real_escape_string($_POST["email"], $connection);
	$pass = mysql_real_escape_string($_POST["pass"], $connection);
	
	// Make arrays
	$_SESSION["errors"] = array();
	$_SESSION["form"] = array();
	
	// Email validation
	If (empty($email))	
		$_SESSION["errors"]["email"] = "Email is empty";
	
	else if (!preg_match('/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $email))
		$_SESSION["errors"]["email"] = "Email not a valid format";
	
	else if (strlen($email) > 50)
		$_SESSION["errors"]["email"] = "Maximum 50 characters";	
		
	else
	{
		$_SESSION["form"]["email"] = $email;
		unset($_SESSION["errors"]["email"]);
	}
		
	// Password validation
	If (empty($pass))	
		$_SESSION["errors"]["pass"] = "Password is empty";	
	
	else if (strlen($pass) > 20)
		$_SESSION["errors"]["pass"] = "Maximum 20 characters";	
		
	else	
	{
		$_SESSION["form"]["pass"] = $pass;
		unset($_SESSION["errors"]["pass"]);
	}
	
	// If there were any errors, show the page again
	if (count($_SESSION["errors"]))
	{
		mysql_close($connection); // Close connection
		header("Location: login.php");
		exit;
	}


	
	// Try login
	$result = login($email, $pass);
	
	if ($result == TRUE)
		header("Location: loginreceipt.php?result=success");	
	else
		header("Location: loginreceipt.php?result=failed");			

	mysql_close($connection); // Close connection

	
// ******************************************************
	/**
	 *@desc This function logs in the user using the suer defined user and password.
	 *@param string $email 
	 *@param string $pass
	 */
function login($email, $pass)
{

	global $connection; // make accessible in function
	
	// Try and find email
	$query = "SELECT user_id, firstname, email, password, role FROM users WHERE email='" . $email . "'";
	
	// Run query to find email
	if ($result = mysql_query ($query, $connection))
	{
		$row = mysql_fetch_array($result); // Get data into row
		
		If (mysql_num_rows($result) == 1) // Get how many rows returned		 
		{		
			if (md5($pass) == $row["password"])
			{
				// Password corrent, Success
				$_SESSION["user_id"] = $row["user_id"];
				$_SESSION["firstname"] = $row["firstname"];
				$_SESSION["role"] = $row["role"];
				
				return TRUE;
			}
			else
				//Password wrong
				return FALSE;
				
		}
		else
			// User doesn't exists
			return FALSE;
			
	}	
	else
		// Query failed
		die ("Query failed");
}
	
?>
